var morgan = require('morgan');//引用依赖
var path = require('path');
var FileStreamRotator = require('file-stream-rotator');//日志文件分割
var fs = require('fs');
var hmorgan = {}
////自定义 morgan token
morgan.token('httpData', function (req, res) {
    var httpData = {};
    if (req.method == 'GET') {
        httpData = req.query;
    } else {
        httpData = req.body;
    }
    return JSON.stringify(httpData);
})
morgan.token('time', function (req, res) {
    return (new Date()).Format("yyyy-MM-dd hh:mm:ss");
})
morgan.token('ip', function (req, res) {
    return req._remoteAddress || "--";
})
morgan.token('errorDetail', function (req, res) {
    return req._remoteAddress || "--";
})

//自定义 morgan format
morgan.format('hcsy', '[hcsy] :time :method :url :status :httpData');//打印成功【自定义log输出格式】 eg:[hcsy] 2018-11-12 16:29:23 GET /about?num=33 304 {"num":"33"} 这些都是全局的 

morgan.format('info', '[morgan-info] :ip :time :method :url :status :httpData');
morgan.format('error', '[morgan-error] :time :method :url :status :httpData :response-time');//:response-time 表示服务响应时间


var logDirectory = path.join(__dirname, '../log')
fs.existsSync(logDirectory) || fs.mkdirSync(logDirectory)//判断是否存在文件，不存在即创建
//error 的日志文件
var accessLogStream = FileStreamRotator.getStream({
    date_format: 'YYYY-MM-DD',// 日志文件按小时记录
    filename: path.join(logDirectory, 'error-%DATE%.log'),
    frequency: 'daily',
    verbose: false
})
//info 的日志文件
var accessLogStreamInfo = FileStreamRotator.getStream({
    date_format: 'YYYY-MM-DD',// 日志文件按小时记录
    filename: path.join(logDirectory, 'info-%DATE%.log'),
    frequency: 'daily',
    verbose: false
})
//warn 的日志文件
var accessLogStreamWarn = FileStreamRotator.getStream({
    date_format: 'YYYY-MM-DD',// 日志文件按小时记录
    filename: path.join(logDirectory, 'info-%DATE%.log'),
    frequency: 'daily',
    verbose: false
})

hmorgan = {
    error: morgan('error', {
        skip: function (req, res) { return res.statusCode < 400 },
        stream: accessLogStream
    }),
    info: function () {
        return morgan('info', {
            skip: function (req, res) { },
            stream: accessLogStreamInfo
        })
    },
    accessLogStream:accessLogStream,
    accessLogStreamInfo:accessLogStreamInfo
}

module.exports = hmorgan;